<script setup lang="ts">
import { ref, watch } from 'vue';
import { $t } from '@/locales';
import DeptTreeSelect from '@/views/system/dept/modules/dept-tree-select.vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { fetchGetUserPostList, fetchSaveUserDeptBatch } from '@/service/api';
import { useLoading } from '~/packages/hooks';

defineOptions({ name: 'UserDeptDialog' });

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

interface Props {
  currentDeptId: CommonType.IdType;
  userList: Array<Api.System.User.UserInfoRecord>;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

type FormModel = Api.System.User.UserDeptOperateModel;

function createDefaultModel(): FormModel {
  return {
    deptId: '',
    currentDeptId: props.currentDeptId,
    post: '',
    orderNum: undefined,
    userList: props.userList || []
  };
}

const { formRef, validate, restoreValidation } = useForm();
const { createRequiredRule } = useFormRules();

const model = ref<FormModel>(createDefaultModel());

// 初始化
function handleInitModel() {
  model.value = createDefaultModel();
}

type RuleKey = Extract<FormModel, 'deptId' | 'isLeave'>;
const rules = ref<Record<RuleKey, App.Global.FormRule>>({
  deptId: createRequiredRule('请选择要加入的部门'),
  isLeave: createRequiredRule('必选')
});

const { loading, startLoading, endLoading } = useLoading(false);

async function handleSubmit() {
  try {
    await validate();
    startLoading();
    // request
    const { error } = await fetchSaveUserDeptBatch(model.value);
    // success
    if (error) return;
    window.$message?.success($t('common.operateSuccess'));
    closeDialog();
    emit('submitted');
  } finally {
    endLoading();
  }
}

// 关闭对话框
function closeDialog() {
  visible.value = false;
}

// 用户岗位列表
const userPostList = ref<Api.System.User.UserPostRecord[]>();

// 获取部门类型
async function getUserPostList() {
  const { data, error } = await fetchGetUserPostList();
  if (error) return;
  userPostList.value = data;
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getUserPostList();
  }
});
</script>

<template>
  <ElDialog v-model="visible" title="切换部门" width="600" :close-on-click-modal="false">
    <ElForm ref="formRef" v-loading="loading" :model="model" :rules="rules" :label-width="80" label-position="top">
      <ElFormItem label="用户部门" prop="deptId">
        <DeptTreeSelect v-model="model.deptId" :disabled-chilren-id="model.currentDeptId" placeholder="选择部门" />
      </ElFormItem>
      <ElFormItem label="用户岗位" prop="post">
        <ElSelect v-model="model.post" placeholder="选择岗位">
          <ElOption v-for="item in userPostList" :key="item.id" :value="item.code" :label="item.name" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem :label="$t('form.orderNum')" prop="orderNum">
        <ElInputNumber
          v-model="model.orderNum"
          :placeholder="$t('form.orderNum')"
          :step="10"
          controls-position="right"
          :precision="0"
          class="wfull"
        />
      </ElFormItem>
      <ElFormItem label="是否退出当前部门" prop="isLeave">
        <ElRadioGroup v-model="model.isLeave">
          <ElRadio :value="1" label="是" />
          <ElRadio :value="0" label="否" />
        </ElRadioGroup>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElSpace v-loading="loading" :size="16">
        <ElButton @click="closeDialog">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </ElDialog>
</template>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
